<?php

namespace app\http\middleware\befor;

use Laf\Session;
use mon\env\Config;
use app\model\AdminModel;

/**
 * AdminLogin 前置中间件，验证管理端登录态
 *
 * Class AdminLogin
 * @copyright 2021-03-24 mon-console
 * @version 1.0.0
 */
class AdminLogin
{
	/**
	 * 回调方法
	 *
	 * @param mixed $val 依赖参数
	 * @param \FApi\App $app APP实例
	 * @return boolean 返回true执行后续操作
	 */
	public function handler($val, $app)
	{
		$userInfo = Session::instance()->get(Config::instance()->get('admin.admin_session_key'));
		if (!$userInfo) {
			$loginURL = $app->url->build('/admin/login');
			return $app->url->redirect($loginURL);
		}
		// 开启单点登录
		if (Config::instance()->get('admin.sign_in') && !in_array($userInfo['id'], Config::instance()->get('admin.sign_in_filter', []))) {
			$info = AdminModel::instance()->getInfo(['id' => $userInfo['id'], 'login_token' => $userInfo['login_token']]);
			if (!$info) {
				$loginURL = $app->url->build('/admin/login');
				return $app->url->abort(401, '您的账号在异地登录，如非本人操作请修改密码并<a href="' . $loginURL . '">重新登录</a>');
			}
		}
		return true;
	}
}
